package com.czwx.bee.business.manager.modular.sys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.czwx.bee.base.common.interfaces.BpUserStatusEnum;
import com.czwx.bee.base.common.utils.MD5Util;
import com.czwx.bee.business.manager.modular.main.dto.LoginDto;
import com.czwx.bee.business.manager.modular.sys.dto.UserDto;
import com.czwx.bee.business.manager.modular.sys.mapper.UserDao;
import com.czwx.bee.business.manager.modular.sys.model.SecurityUser;
import com.czwx.bee.business.manager.modular.sys.model.User;
import com.czwx.bee.business.manager.modular.sys.service.UserService;
import com.czwx.bee.business.manager.utils.SecurityUtil;
import org.beetl.sql.core.Params;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.beetl.sql.core.db.KeyHolder;
import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;

    @Autowired
    SQLManager sqlManager;


    @Transactional
    public Long insert(User user) {
        SecurityUser securityUser=SecurityUtil.getSecurityUser();
        user.setPassword(MD5Util.getMd5Value(user.getPassword()));
        user.setCreateTime(new Date());
        user.setCreateBy(securityUser.getId());
        KeyHolder keyHolder=userDao.insertReturnKey(user);
        if(keyHolder!=null&&!StrUtil.isEmpty(user.getRid())){
            authUser(keyHolder.getLong(),user.getRid());
        }

        return keyHolder.getLong()>0?keyHolder.getLong():null;
    }

    @Transactional
    public Boolean update(User user) {
        SecurityUser securityUser=SecurityUtil.getSecurityUser();
        user.setUpdateBy(securityUser.getId());
        if(user.getPassword()!=null){
            user.setPassword(MD5Util.getMd5Value(user.getPassword()));
        }
        user.setUpdateTime(new Date());
       Integer rs= userDao.updateTemplateById(user);
        if(rs>0&&!StrUtil.isEmpty(user.getRid())){
            authUser(user.getId(),user.getRid());
        }
        return rs>0?true:false;
    }

    @Transactional
    public Boolean del(User user) {
        return null;
    }

    @Override
    public User getById(Long id) {
        return userDao.single(id);
    }

    @Override
    public List<User> getList(Map map) {
        return userDao.all();
    }

    @Override
    public void getPageList(PageQuery query) {
        sqlManager.pageQuery("user.pageQuery",UserDto.class,query);
    }

    @Override
    public Long getCount(User user) {
        return null;
    }

    @Override
    public User getBySelf(User user) {
        return userDao.templateOne(user);
    }
    @Transactional
    @Override
    public Boolean disableDrainage(Long id) {
        String sql="update bp_user set status=? where drainage_id=?";
     Integer rs=   sqlManager.executeUpdate(new SQLReady(sql,BpUserStatusEnum.Discontinuation.getCode(),id));
        return rs>0?true:false;
    }

    @Override
    public Boolean checkShopRegist(User user) {
        Query<User> query = sqlManager.query(User.class);
        sqlManager.query(User.class).orEq("drainage_id",user.getDrainageId()).orEq("login_name",user.getLoginName());
        return null;
    }

    @Override
    public Long saveOrUpdate(User user) {
        if(!StrUtil.isEmptyIfStr(user.getId())){
            update(user);
            return user.getId();
        }
        else {
            return this.insert(user);
        }
    }

    @Override
    public Boolean authUser(Long id, String ids) {
        String[] rids=ids.split(",");
        String sql="delete from bp_user_role where user_id=#id#";
        sqlManager.executeUpdate(sql,Params.ins().add("id",id).map());

        sql="INSERT INTO bp_user_role (user_id,role_id) VALUES ";
        for(int i=0;i<rids.length;i++){
            sql+="("+id+","+rids[i]+")";
            if(i!=rids.length-1){
                sql+=",";
            }
        }
        if(sqlManager.executeUpdate(sql,null)==0){
            return  false;
        }
        return true;
    }

    @Override
    public SecurityUser getAuthUser(String username) {
         String sql="SELECT a.id,a.login_name AS username,a.password,a.drainage_id,a.user_type,a. name AS realName,a.status,b. name AS companyName " +
                "FROM bp_user a LEFT JOIN cl_drainage_platform b ON a.drainage_id = b.id where a.login_name=#username#";
         List<SecurityUser> list=sqlManager.execute(sql,SecurityUser.class,Params.ins().add("username",username).map());
         if(list.size()==0){
              return null;
         }
         else {
           return   list.get(0);
         }
    }

    @Override
    @Transactional
    public Boolean resetPwd(String ids) {
        String pwd=MD5Util.getMd5Value("123456");
        String sql="UPDATE bp_user SET password =#pwd# WHERE id in("+ids+")";
        sqlManager.executeUpdate(sql,Params.ins().add("ids",ids).add("pwd",pwd).map());
        return null;
    }

    @Override
    @Transactional
    public Boolean changeStatus(Integer type, String ids) {
        String sql="UPDATE bp_user SET status =#type# WHERE id in("+ids+")";
        sqlManager.executeUpdate(sql,Params.ins().add("type",type).map());
        return null;
    }
}
